package com.nku.mason.lucene.optimization;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;

import com.nku.mason.lucene.entity.Article;
import com.nku.mason.lucene.util.LuceneUtil;

/**
 * 索引库优化，速度问题(建立内存索引库，并双向同步)
 * @author Mason
 * 
 */
public class RamIndexDB {
	
	public void createIndexDBWithRam() throws Exception{
		Article article = new Article(1,"南开","南开大学啥时候放假");
		//创建文件系统索引库路径
		Directory fsDirectory = FSDirectory.open(new File("E:/TestDirectory/IndexDBa"));
		//创建RAM索引库路径基于文件系统索引库,用于将文件系统中的索引库加载到内存中
		Directory ramDirectory = new RAMDirectory(fsDirectory);
		//创建文件系统索引库的indexWriter,第三个参数设置为true将使ram索引库同步到文件系统时进行覆盖
		IndexWriter fsIndexWriter = new IndexWriter(fsDirectory , LuceneUtil.getAnalyzer(), true, LuceneUtil.getMaxFieldLength());
		//创建ram索引库的indexWriter
		IndexWriter ramIndexWriter = new IndexWriter(ramDirectory, LuceneUtil.getAnalyzer(), LuceneUtil.getMaxFieldLength());
		
		ramIndexWriter.addDocument(LuceneUtil.javabean2Document(article));
		ramIndexWriter.close();
		System.out.println("New Document added to indexDB in RAM...");
		//将内存索引库中的内容同步到文件系统中
		fsIndexWriter.addIndexesNoOptimize(ramDirectory);
		fsIndexWriter.close();
		System.out.println("Content in RAM indexDB is copyed into FileSystem...");
	}
	
	//查询
	public void searchForKeyword(String keyword) throws Exception{
		List<Article> list = new ArrayList<>();
		Directory ramDirectory = new RAMDirectory(LuceneUtil.getDirectory());
		IndexSearcher indexSearcher = new IndexSearcher(ramDirectory);
		QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(), "content", LuceneUtil.getAnalyzer());
		Query query = queryParser.parse(keyword);
		TopDocs topDocs = indexSearcher.search(query, 100);
		for(int i=0;i<topDocs.scoreDocs.length;i++){
			int no = topDocs.scoreDocs[i].doc;
			Document document = indexSearcher.doc(no);
			Article article = (Article) LuceneUtil.document2JavaBean(document, Article.class);
			list.add(article);
		}
		indexSearcher.close();
		
		for(Article a:list){
			System.out.println(a);
		}
	}
	
	public static void main(String[] args) throws Exception {
		RamIndexDB test = new RamIndexDB();
//		test.createIndexDBWithRam();
		test.searchForKeyword("南");
	}
}


































































